package src.javaStudy.Collection.ArrayList;

/**
 * @program: AlgorithmTest
 * @description: 手写arrayList实现
 * @author: powerWriter
 * @create: 2019-07-05 19:30
 **/
public class ArrayListByWriter {
    private Object[] array;
    private int indexPos = 0;

    /**
     * 初始化数组长度
     */
    public ArrayListByWriter(){
        this.array = new Object[10];
    }

    /**
     * 初始化指定长度
     */
    public ArrayListByWriter(int size){
        this.array = new Object[size];
    }

    /**
     * 添加数据
     */
    public void add(Object e){
        isCapacity();
        this.array[indexPos] = e;
        indexPos ++;
    }

    /**
     * 获取当前数组的长度
     */
    public int getListSize(){
        return this.array.length;
    }

    /**
     * 获取已经添加的数据数量
     */
    public int getSize(){
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                count ++;
            }
        }
        return count;
    }

    /**
     * 插入数据到指定位置
     */
    public void insert(int index,Object e){
        isCapacity();

        Object[] tempArray = new Object[array.length];

        for (int i = 0; i < index; i++) {
            tempArray[i] = array[i];
        }
        tempArray[index] = e;
        tempArray[index+1] = array[index];
        for (int i = index+2; i < array.length; i++) {
            tempArray[i] = array[i-1];
        }
        this.array = tempArray;
        indexPos ++;
    }

    /**
     * 判断是否扩容
     * 扩容为原来的1.5倍长度
     */
    public void isCapacity(){
        if(indexPos >= array.length){
            int newSize = array.length/2*3;
            Object[] newArray = new Object[newSize];
            for (int i = 0; i < array.length; i++) {
                newArray[i] = array[i];
            }
            this.array = newArray;
        }
    }

    /**
     * 显示数据
     * @param content
     */
    public void showData(String content){
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                System.out.println(content+array[i]);
            }
        }
    }


}
